package com.vogue.supplymall.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.vogue.supplymall.common.domain.jacksonutil.DateSerializer;
import com.vogue.supplymall.common.domain.jacksonutil.NumberSerializer;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018-01-23.
 */
public class JacksonConvert {

    public static void convert(List<HttpMessageConverter<?>> converters) {
        int len=converters.size();
        int idx=0;
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter =null;
        for (;idx<len;idx++){
            HttpMessageConverter con=converters.get(idx);
            if(con instanceof MappingJackson2HttpMessageConverter){
                jackson2HttpMessageConverter=(MappingJackson2HttpMessageConverter)con;
                break;
            }
        }
        if(jackson2HttpMessageConverter==null){
            idx=0;
            jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        }
//        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Date.class, DateSerializer.instance);//注册日期序列化方法
        simpleModule.addSerializer(Number.class, new NumberSerializer(Number.class , true) );//注册数值序列化方法,true为long转string
        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(idx,jackson2HttpMessageConverter);//必须放在第一位才能生效
    }
}
